<template>
  <a-tabs v-model:activeKey="activeKey" type="card" style="padding: 0" class="container-left" @change="onTabChange">
    <a-tab-pane v-for="pane in tabs" :key="pane.id" :tab="pane.name" :disabled="loading">
      <!-- 部门维度   -->
      <!-- <a-spin :spinning="loading" class="container-left-spin"> -->
      <template v-if="pane.type == 'dept' || viewType == 'tree'">
        <a-input-search
          :ref="'searchInput' + pane.type"
          :placeholder="searchPlaceholder"
          allow-clear
          style="width: 100%; margin-bottom: 8px"
          @search="handleSearch"
        />
        <a-tree
          v-if="treeData.length > 0 && showDeptTree"
          v-model:checkedKeys="treeCheckedKeys"
          v-model:selectedKeys="treeCheckedKeys"
          v-model:expandedKeys="realExpandedKeys"
          :height="leftTreeHeight"
          :multiple="selectModel !== 'single'"
          :checkable="selectModel !== 'single'"
          :load-data="loadDataAsyn"
          :tree-data="treeData"
          :loaded-keys="treeLoadedKeys"
          :show-line="true && { showLeafIcon: false }"
          :show-icon="false"
          @select="onSelect"
          @check="onCheck"
          @expand="onExpand"
          @load="onLoad"
        >
          <template v-slot:title="{ dataRef }">
            <!-- 选人组件图标 -->
            <span class="user-icon">
              <avic-icon v-if="dataRef.nodeType == 'user'" svg="avic-user-line" class="tree-icon users-icon" />
              <avic-icon v-else-if="dataRef.nodeType == 'role'" svg="avic-contacts-line" class="tree-icon role-icon" />
              <avic-icon v-else-if="dataRef.nodeType == 'group'" svg="avic-group-line" class="tree-icon group-icon" />
              <avic-icon v-else-if="dataRef.nodeType == 'position'" svg="avic-user-2-line" class="tree-icon position-icon" />
              <avic-icon v-else-if="dataRef.nodeType == 'dept'" svg="avic-organization-chart" class="tree-icon dept-icon" />
              <avic-icon v-else svg="avic-building-line" class="tree-icon org-icon" />
            </span>
            <span class="more-user-info" :title="getTitle(dataRef)">
              <span v-if="dataRef.nodeType == 'user' && dataRef.title.indexOf(keyword) > -1">
                {{ dataRef.title.substr(0, dataRef.title.indexOf(keyword)) }}
                <span style="color: #f50">{{ keyword }}</span>
                {{ dataRef.title.substr(dataRef.title.indexOf(keyword) + keyword.length) }}
              </span>
              <span v-else>
                {{ dataRef.title }}
              </span>
              <span v-if="showMoreUserInfo" style="color: #86909c">
                <slot v-if="dataRef.nodeType == 'user'" name="moreInfo" :user-side-info="dataRef.attributes">
                  {{ getAttributes(dataRef) }}
                </slot>
              </span>
            </span>
          </template>
        </a-tree>
      </template>
      <!-- </a-spin> -->
      <!-- 群组、角色、岗位维度的用户   -->
      <template v-if="pane.type != 'dept' && viewType == 'table'">
        <div class="search-box">
          <a-select
            v-if="treeData.length > 0"
            v-model:value="selectOptionId"
            :placeholder="'请选择' + placeholderMap[pane.type]"
            style="width: 50%; margin-bottom: 10px; margin-right: 10px; border-radius: 4px"
            :show-search="true"
            :filter-option="filterOption"
            @change="handleChange"
          >
            <a-select-option v-for="item in treeData" :key="item.id" :value="item.id" :title="item.title">
              {{ item.title }}
            </a-select-option>
          </a-select>
          <a-input-search
            :ref="'searchInput' + pane.type"
            v-model:value="keyword"
            :placeholder="searchPlaceholder"
            allow-clear
            style="width: 50%; margin-bottom: 8px"
            @search="handleKeyWordQuery"
          />
        </div>
        <div class="container-checkbox container-table table-wrapper">
          <s-table
            v-model:pagination="pagination"
            row-key="key"
            :loading="tableLoading"
            :row-height="36"
            :bordered="false"
            :show-header="false"
            :columns="columns"
            :data-source="userTableList"
            :scroll="{ y: 320 }"
            :row-selection="{
              type: selectModel != 'single' ? 'checkbox' : 'radio',
              selectedRowKeys: selectedRowKeys,
              onSelect: onSelectChange,
              columnWidth: selectModel != 'single' ? 32 : 0
            }"
            :custom-row="
              (record) => {
                return {
                  onClick: () => {
                    handleRowSelection(record);
                  },
                  onDblclick: (event) => {
                    handleDbclickSelection(record);
                  }
                };
              }
            "
            @change="handleTableChange"
          >
            <template #bodyCell="{ record }">
              <span class="user-icon">
                <avic-icon svg="avic-contacts-line" class="tree-icon role-icon" />
              </span>
              <span class="cell-txt" :title="record['title']">
                <span>{{ record['title'] }}</span>
                <span v-if="showMoreUserInfo" style="color: #86909c">
                  <slot name="moreInfo" :user-side-info="record.attributes">
                    {{ getAttributes(record) }}
                  </slot>
                </span>
              </span>
            </template>
          </s-table>
          <div v-if="selectModel !== 'single' && userTableList.length > 0" class="pagination-box">
            <a-checkbox
              v-model:checked="state.checkAll"
              :indeterminate="selectedRowKeys.length > 0 && selectedRowKeys.length < userTableList.length"
              @change="handleCheckAllChange"
            />
          </div>
        </div>
      </template>
      <a-empty v-if="treeData.length == 0 && loading == false" :image="simpleImage" />
      <!-- </a-spin> -->
    </a-tab-pane>
  </a-tabs>

  <div class="container-right">
    <div class="container-right-top">
      已选{{ name + ` (` + selectLength + `)` }}
      <delete-outlined class="total-delete-icon" title="清空" @click="handleDelTotal" />
    </div>
    <div class="checkgroup table-wrapper">
      <s-table
        row-key="id"
        :columns="selectColumns"
        :data-source="selectList"
        :pagination="false"
        :show-header="false"
        :row-height="36"
        :height="rightTreeHeight"
        children-column-name="hasChild"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'title'">
            <span class="cell-txt" style="display: inline-flex">
              <avic-icon svg="avic-user-line" class="tree-icon users-icon" />
              <span class="more-user-info" :title="getTitle(record)">
                <span>{{ text }}</span>
                <span v-if="showMoreUserInfo" style="color: #86909c">
                  <slot v-if="record.nodeType == 'user'" name="moreInfo" :user-side-info="record.attributes">
                    <!-- showMoreUserInfo 为true ，显示全部 moreUserInfo 中的信息 -->
                    <span
                      v-if="typeof showMoreUserInfo == 'boolean' && moreUserInfo.length > 0 && record.attributes[moreUserInfo[0]]"
                      style="display: inline-block"
                    >
                      (
                      <span v-for="(infoItem, index) in moreUserInfo" :key="infoItem">
                        {{ record.attributes[infoItem] }}
                        <span v-if="index < moreUserInfo.length - 1">/</span>
                      </span>
                      )
                    </span>
                    <!-- showMoreUserInfo 为数组，仅显示 showMoreUserInfo 对应的属性值 -->
                    <span v-else-if="typeof showMoreUserInfo == 'object'">
                      (
                      <span v-for="(infoItem, index) in showMoreUserInfo" :key="infoItem">
                        {{ record.attributes[infoItem] || '' }}
                        <span v-if="record.attributes[infoItem] && index < showMoreUserInfo.length - 1">/</span>
                      </span>
                      )
                    </span>
                    <!--上述不满足，显示部门信息 -->
                    <span v-else>
                      {{ record.attributes && record.attributes.deptname ? '(' + record.attributes.deptname + ')' : '' }}
                    </span>
                  </slot>
                </span>
              </span>
            </span>
            <span class="checkclose" title="删除" @click="handleDelItem($event, record)">
              <avic-icon svg="avic-close-fill" />
            </span>
          </template>
        </template>
      </s-table>
    </div>
  </div>
</template>
<!-- eslint-disable max-lines -->
<script lang="ts" setup>
import { Empty } from 'ant-design-vue';
import { httpRequest, listCommonSelectUserByPage } from './api';
import { uuid } from '@/utils/common-util';

const { proxy } = getCurrentInstance();
const props = defineProps({
  /** 是否显示 */
  show: { type: Boolean, default: false },
  /** 右侧列表已选标题文案 */
  name: { type: String, default: '人员' },
  /** 标题 */
  title: { type: String, default: '人员选择' },
  /** 辅助提示信息 */
  titleTips: { type: String, default: '' },
  /** 搜索提示 */
  searchPlaceholder: { type: String, default: '请输入用户姓名或拼音或登录名查询' },
  /** 单选 single ，多选 multi */
  selectModel: { type: String, default: 'single' },
  /** 多选最多选择数量 */
  maxSelect: { type: Number, default: 0 },
  /** 默认值 */
  defaultValue: { type: [Object, String], default: '' },
  /** 双向绑定值 */
  modelChange: {
    type: Object,
    default: () => ({ ids: '', names: '' })
  },
  /** tab页签集合 */
  userSelectTabs: { type: Array, default: () => ['dept', 'group', 'role', 'position'] },
  /** 展示人员的额外信息 */
  moreUserInfo: { type: Array, default: () => [] },
  /** 是否展示人员附加信息 */
  showMoreUserInfo: { type: [Boolean, Array], default: true },
  /** 人员附加信息可选列表 */
  moreUserInfoList: { type: Array, default: () => [] },
  /** 组织范围 */
  viewScope: { type: String, default: '' },
  /** 默认加载组织id */
  defaultOrgId: { type: String, default: '' },
  /** 默认加载部门id */
  defaultLoadDeptId: { type: String, default: '' },
  /** 默认加载群组id */
  defaultLoadGroupId: { type: String, default: '' },
  /** 默认加载角色id */
  defaultLoadRoleId: { type: String, default: '' },
  /** 默认加载岗位id */
  defaultLoadPositionId: { type: String, default: '' },
  /** 选人-文档密级过滤 */
  secretLevel: { type: String, default: '' },
  /** 选人-人员密级过滤 */
  userSecretLevel: { type: String, default: '' },
  /** 是否展示无效用户 */
  viewSystemUser: { type: Boolean, default: false },
  /** 部门tab页初始展开层级 */
  deptTabExpandLevel: { type: Number, default: 2 },
  /** 关键字查询时最大用户数限制 */
  searchNumLimit: { type: Number, default: 200 },
  /** 自定义参数 */
  customParam: { type: Object, default: () => ({}) },
  /** 搜索自定义参数 */
  customSearchParam: { type: Object, default: () => ({}) },
  /** 获取初始化用户信息请求地址 */
  getInitUserInfoUrl: { type: String, default: '/appsys/common/select/getSelectedUserInfo/v1' },
  /** 获取初始化用户信息请求类型 */
  getInitUserInfoMethod: { type: String, default: 'post' },
  /** 用户请求地址 */
  userUrl: { type: String, default: '/appsys/common/select/getUserSelectList/v1' },
  /** 用户请求类型 */
  methodType: { type: String, default: 'post' },
  /** 搜索用户请求地址 */
  userSearchUrl: { type: String, default: '/appsys/common/select/getUserSelectList/v1' },
  leftTreeHeight: { type: Number, default: 350 },
  rightTreeHeight: { type: Number, default: 400 },
  /** 根据业务需要过滤可选人员数据的接口(sync) */
  filterUser: { type: Function, default: null },
  /** check时选中孙子节点,打开时会层层异步加载子节点的子节点，关闭时只加载一层子节点 */
  checkChildenNode: { type: Boolean, default: true },
  /** 用户、角色、群组、岗位三个维度待选区的展示视图类型 table tree  */
  viewType: { type: String, default: 'tree' }
});

// const visible = ref(false);
const tabs = ref([]);
const tabsMap = {
  dept: { id: '1', name: '部门', type: 'dept' },
  group: { id: '2', name: '群组', type: 'group' },
  role: { id: '3', name: '角色', type: 'role' },
  position: { id: '4', name: '岗位', type: 'position' }
};
const activeKey = ref('1');
let currentTab = 'dept';
let loadedTabs = ['dept'];
const treeParam = {
  url: props.userUrl,
  parameter: {},
  method: props.methodType
};
const searchTreeParam = {
  url: props.userSearchUrl,
  parameter: {},
  method: props.methodType
};
const keyword = ref('');
const keywordDept = ref('');
const keywordGroup = ref('');
const keywordRole = ref('');
const keywordPosition = ref('');
const searchResultFlag = ref(false);
const searchResultFlagDept = ref(false);
const searchResultFlagGroup = ref(false);
const searchResultFlagRole = ref(false);
const searchResultFlagPosition = ref(false);
const treeData = ref([]);
const treeDataDept = ref([]);
const treeDataGroup = ref([]);
const treeDataRole = ref([]);
const treeDataPosition = ref([]);
const treeCheckedKeys = ref([]);
const realExpandedKeys = ref([]); // 树节点最终使用的展开节点key集合
const treeExpandedKeys = ref([]);
const treeExpandedKeysDept = ref([]);
const treeExpandedKeysGroup = ref([]);
const treeExpandedKeysRole = ref([]);
const treeExpandedKeysPosition = ref([]);
const treeLoadedKeys = ref([]);
const treeLoadedKeysDept = ref([]);
const treeLoadedKeysGroup = ref([]);
const treeLoadedKeysRole = ref([]);
const treeLoadedKeysPosition = ref([]);
const selectColumns = ref([
  {
    title: '已选人员',
    dataIndex: 'title',
    rowDrag: () => !!(props.selectModel === 'multi' && proxy.$settings.commonSelectExtends.selectedUserSortable)
  }
]);
const selectList = ref([]);
let selectListMap = {};
const selectLength = ref(0);
const treeClickCount = ref(0); // 树点击次数
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const loading = ref(false);
let needCheckedKeys = []; // 缓存需要选中的子节点

const tableLoading = ref(false);
const placeholderMap = {
  role: '角色',
  group: '群组',
  position: '岗位'
};
const selectOptionId = ref(null); // 下拉框选中的id
const selectOption = ref(null); // 下拉框选中对象
const columns = [
  {
    title: '名称',
    dataIndex: 'title',
    key: 'id'
  }
];
const userTableList = ref([]);
const selectedRowKeys = ref([]);
const pagination = reactive({
  size: 'small',
  current: 1,
  pageSize: 20,
  // s-table组件内部的defaultPageSize默认值与指定的pageSize不一致时，会在初始化时触发一次change事件，导致重复请求
  defaultPageSize: 20,
  total: 0,
  showLessItems: true,
  hideOnSinglePage: true,
  position: ['bottomCenter'],
  showSizeChanger: true
});
const queryParam = reactive({
  // 请求表格数据参数
  pageParameter: {
    page: 1, // 页数
    rows: 20 // 每页条数
  },
  searchParams: {
    searchText: ''
  },
  sidx: null, // 排序字段
  sord: null // 排序方式: desc降序 asc升序
});
const state = reactive({
  checkAll: false,
  indeterminate: true
});
watch(
  () => props.show,
  (newV) => {
    // visible.value = newV;
    if (newV === true) {
      init();
    }
  },
  { immediate: true }
);
watch(
  () => props.userSelectTabs,
  (newV) => {
    if (newV && newV.length > 0) {
      const list = [];
      newV.forEach((tim: string) => {
        list.push(tabsMap[tim]);
        return tim;
      });
      tabs.value = list;
      activeKey.value = tabs.value[0].id;
      currentTab = tabs.value[0].type;
      loadedTabs = [tabs.value[0].type];
    }
  },
  { immediate: true }
);
watch(
  () => props.defaultValue,
  (defaultValue) => {
    if (defaultValue && defaultValue.ids) {
      const ids = defaultValue.ids.split(';');
      let names = [];
      if (defaultValue.names) {
        names = defaultValue.names.split(';');
      }
      if (ids.length === names.length) {
        initDataNotHttp(defaultValue);
      } else {
        loadDefaultValue(defaultValue.ids);
      }
    } else if (Object.prototype.toString.call(defaultValue) === '[object String]') {
      loadDefaultValue(defaultValue);
    }
  },
  { immediate: true }
);
watch(
  () => props.modelChange,
  (newV, oldV) => {
    // 值没有变化不做更新
    if (oldV && oldV.ids && newV.ids === oldV.ids) return;
    if (newV && newV.ids) {
      const ids = newV.ids.split(';');
      let names = [];
      if (newV.names) {
        names = newV.names.split(';');
      }
      if (ids.length === names.length) {
        initDataNotHttp(newV);
      }
    } else {
      if (selectList.value.length > 0) {
        emptySelect();
      }
    }
  },
  { immediate: true, deep: true }
);
watch(
  selectList,
  (newV) => {
    selectLength.value = newV.length;
  },
  { immediate: true }
);
watch(
  keyword,
  (newV) => {
    if (currentTab === 'dept') {
      keywordDept.value = newV;
    } else if (currentTab === 'group') {
      keywordGroup.value = newV;
    } else if (currentTab === 'role') {
      keywordRole.value = newV;
    } else if (currentTab === 'position') {
      keywordPosition.value = newV;
    }
  },
  { immediate: true }
);
watch(
  treeExpandedKeys,
  (newV) => {
    realExpandedKeys.value = [...newV];
    if (currentTab === 'dept') {
      treeExpandedKeysDept.value = [...newV];
    } else if (currentTab === 'group') {
      treeExpandedKeysGroup.value = [...newV];
    } else if (currentTab === 'role') {
      treeExpandedKeysRole.value = [...newV];
    } else if (currentTab === 'position') {
      treeExpandedKeysPosition.value = [...newV];
    }
  },
  { immediate: true }
);
watch(
  treeLoadedKeys,
  (newV) => {
    if (currentTab === 'dept') {
      treeLoadedKeysDept.value = [...newV];
    } else if (currentTab === 'group') {
      treeLoadedKeysGroup.value = [...newV];
    } else if (currentTab === 'role') {
      treeLoadedKeysRole.value = [...newV];
    } else if (currentTab === 'position') {
      treeLoadedKeysPosition.value = [...newV];
    }
  },
  { immediate: true }
);
watch(
  searchResultFlag,
  (newV) => {
    if (currentTab === 'dept') {
      searchResultFlagDept.value = newV;
    } else if (currentTab === 'group') {
      searchResultFlagGroup.value = newV;
    } else if (currentTab === 'role') {
      searchResultFlagRole.value = newV;
    } else if (currentTab === 'position') {
      searchResultFlagPosition.value = newV;
    }
  },
  { immediate: true }
);
watch(
  activeKey,
  (newV) => {
    const type = tabs.value.filter((item) => item.id === newV)?.[0]?.type;
    nextTick(() => {
      proxy.$refs[`searchInput${type}`]?.[0]?.focus();
    });
  },
  { immediate: true }
);

onBeforeMount(() => {
  setTreeParameter('', '');
  setTreeSearchParameter('');
});
onMounted(() => {
  // 初始化节点数据
  autoLoadAsyn();
  // 处理默认值
  if (props.defaultValue) {
    const { defaultValue } = props;
    if (defaultValue && defaultValue.ids) {
      const ids = defaultValue.ids.split(';');
      let names = [];
      if (defaultValue.names) {
        names = defaultValue.names.split(';');
      }
      if (ids.length === names.length) {
        initDataNotHttp(defaultValue);
      } else {
        loadDefaultValue(defaultValue.ids);
      }
    } else if (Object.prototype.toString.call(defaultValue) === '[object String]') {
      loadDefaultValue(defaultValue);
    }
  }
});

const $emit = defineEmits(['defaultBack', 'callBack', 'close']);

/** 获取tooltip  */
function getTitle(record) {
  const str = record.title;
  const attributes = getAttributes(record);
  return attributes ? str + attributes : str;
}

/** 获取额外的附件信息组合  */
function getAttributes(record) {
  let str = '';
  if (props.showMoreUserInfo && record.nodeType === 'user') {
    const values = [];
    if (typeof props.showMoreUserInfo == 'boolean' && props.moreUserInfo.length > 0) {
      for (let i = 0; i < props.moreUserInfo.length; i++) {
        if (record.attributes[props.moreUserInfo[i]]) {
          values.push(record.attributes[props.moreUserInfo[i]]);
        }
      }
    } else if (typeof props.showMoreUserInfo == 'object' && props.showMoreUserInfo.length > 0) {
      for (let i = 0; i < props.showMoreUserInfo.length; i++) {
        if (record.attributes[props.showMoreUserInfo[i]]) {
          values.push(record.attributes[props.showMoreUserInfo[i]]);
        }
      }
    }
    if (values.length > 0) {
      str = `(${values.join('/')})`;
    }
  } else {
    str += record.attributes && record.attributes.deptname ? `(${record.attributes.deptname})` : '';
  }
  return str;
}
/**
 * 初始化事件
 */
function init() {
  keyword.value = '';
  setTreeParameter('', '');
  setTreeSearchParameter('');
  if (!props.modelChange.ids) {
    emptySelect();
  }
}
/**
 * 设置加载用户节点需要传的数据
 */
function setTreeParameter(id = '', nodeType = '') {
  treeParam.parameter = {
    viewScope: props.viewScope,
    defaultOrgId: props.defaultOrgId,
    nodeType,
    id,
    currentTab,
    defaultLoadDeptId: props.defaultLoadDeptId,
    defaultLoadGroupId: props.defaultLoadGroupId,
    defaultLoadRoleId: props.defaultLoadRoleId,
    defaultLoadPositionId: props.defaultLoadPositionId,
    viewSystemUser: props.viewSystemUser,
    secretLevel: props.secretLevel,
    userSecretLevel: props.userSecretLevel,
    expandLevel: props.deptTabExpandLevel
  };
  if (Object.keys(props.customParam)) {
    Object.assign(treeParam.parameter, props.customParam);
  }
}
/**
 * 设置搜索用户节点需要传的数据
 */
function setTreeSearchParameter(keyword) {
  const select = [];
  selectList.value.map((tim) => {
    select.push(tim.id);
    return tim;
  });
  searchTreeParam.parameter = {
    viewScope: props.viewScope,
    defaultOrgId: props.defaultOrgId,
    currentTab,
    selectedUser: select.join(','),
    defaultLoadDeptId: props.defaultLoadDeptId,
    defaultLoadGroupId: props.defaultLoadGroupId,
    defaultLoadRoleId: props.defaultLoadRoleId,
    defaultLoadPositionId: props.defaultLoadPositionId,
    viewSystemUser: props.viewSystemUser,
    secretLevel: props.secretLevel,
    userSecretLevel: props.userSecretLevel,
    searchText: keyword,
    numLimit: props.searchNumLimit
  };
  if (Object.keys(props.customSearchParam)) {
    Object.assign(searchTreeParam.parameter, props.customSearchParam);
  }
}
function handleSearch(value) {
  keyword.value = value;
  autoLoadAsyn();
}
/**
 * 自动初始化节点
 */
function autoLoadAsyn() {
  if (!keyword.value) {
    treeExpandedKeys.value = [];
  }
  treeLoadedKeys.value = [];
  searchResultFlag.value = false;
  loadDataAsyn(null);
}
// 加载子节点数据
function loadChildren(list = []) {
  const nodes = list.filter((item) => !item.isLeaf);
  if (nodes.length > 0) {
    const promises = [];
    nodes.forEach((element) => {
      promises.push(loadDataAsyn(element));
    });
    return new Promise((resolve) => {
      Promise.all(promises).then(() => {
        resolve(true);
      });
    });
  }
  return new Promise((resolve) => {
    resolve(true);
  });
}
/**
 * 异步加载数据
 */
function loadDataAsyn(node) {
  return new Promise((resolve) => {
    if (node && node.children && node.children.length > 0) {
      // 如果节点已经加载过，则还需要查询更深一层的节点
      if ((node.checked || needCheckedKeys.includes(node.key)) && props.checkChildenNode) {
        setTimeout(() => {
          checkNodes(node.children);
          needCheckedKeys = needCheckedKeys.filter((item) => item !== node.key);
        }, 0);
      }
      resolve();
      return;
    }
    if (node && !treeLoadedKeys.value.includes(node.id)) {
      treeLoadedKeys.value = [...treeLoadedKeys.value, node.id];
    }
    if (node) {
      setTreeParameter(node.id, node.nodeType);
    } else {
      setTreeParameter('', '');
      // 异步加载全量数据先清空数据；
      loading.value = true;
      treeData.value = [];
    }
    let param = {};
    if (!keyword.value || searchResultFlag.value === true) {
      treeParam.parameter.searchText = '';
      param = treeParam;
    } else {
      setTreeSearchParameter(keyword.value);
      param = searchTreeParam;
    }
    httpRequest(param.url, param.parameter ? param.parameter : '', param.method).then((res) => {
      if (res.success && res.data && res.data.length > 0) {
        // 扩展：根据业务需要过滤可选人员数据
        if (props.filterUser) {
          res.data = props.filterUser(res.data);
        }
        afterLoadData(res);
        if (!node) {
          treeData.value = [...res.data];
          loading.value = false;
          // if (!keyword.value) {
          // 全部展开
          if (currentTab === 'dept') {
            const expandedKeys = [];
            getExpandedKeys(treeData.value, expandedKeys, treeLoadedKeys.value);
            treeExpandedKeys.value = expandedKeys;
          }
          // } else {
          // nextTick(() => {
          //   if (currentTab === 'dept') {
          //     treeExpandedKeys.value = treeData.value ? [treeData.value[0].id] : [];
          //   }
          // });
          // }
        } else {
          if (node.dataRef) {
            node.dataRef.children = res.data;
          } else {
            node.children = res.data;
          }
          treeData.value = [...treeData.value];

          // 设置当前节点及子节点的选中
          if (node.checked || (needCheckedKeys.includes(node.key) && props.checkChildenNode)) {
            const checkChildNode = res.data.filter((item) => item.nodeType === 'user');
            setSelectList(checkChildNode);
            setCheckedData();
          }
          if ((node.checked || needCheckedKeys.includes(node.key)) && props.checkChildenNode) {
            setTimeout(() => {
              checkNodes(res.data);
              needCheckedKeys = needCheckedKeys.filter((item) => item !== node.key);
            }, 0);
          }
        }
        if (currentTab === 'dept') {
          treeDataDept.value = [...treeData.value];
        } else if (currentTab === 'group') {
          treeDataGroup.value = [...treeData.value];
        } else if (currentTab === 'role') {
          treeDataRole.value = [...treeData.value];
        } else if (currentTab === 'position') {
          treeDataPosition.value = [...treeData.value];
        }
        // 加载数据之后回显树选中的数据
        afterLoadToSetTreeCheckedKeys(res.data);
      } else {
        loading.value = false;
        node.isLeaf = true;
        node.dataRef.isLeaf = true;
        if (proxy.$objIsNotBlank(keyword.value)) {
          proxy.$message.warning(res.errorDesc || '未查询到匹配数据！');
          searchResultFlag.value = true;
        } else if (res.errorDesc || node?.title) {
          proxy.$message.warning(res.errorDesc || `${node?.title ?? ''} 节点下无数据。`);
        }
      }
      resolve();
    });
  });
}
// 加载完数据后左侧树选中效果回显
function afterLoadToSetTreeCheckedKeys(list = []) {
  if (currentTab === 'dept' || props.viewType === 'tree') {
    // 回显数据
    if (treeCheckedKeys.value.length > 0) {
      const checkedKeys = [];
      treeCheckedKeys.value.forEach((item) => {
        let itemKeyLength = item.length;
        if (item.length > 32) {
          // 兼容已经加过uuid后的数据
          itemKeyLength = item.length - 32;
        }
        checkedKeys.push(item.substring(0, itemKeyLength));
      });
      list.forEach((item) => {
        const itemKeyLength = item.key.length - 32;
        const itemRealKey = item.key.substring(0, itemKeyLength);
        if (checkedKeys.includes(itemRealKey)) {
          // 替换treeCheckedKeys 中的 key 值 为最新的处理后的key
          treeCheckedKeys.value.splice(checkedKeys.indexOf(itemRealKey), 1, item.key);
        }
        if (treeCheckedKeys.value.includes(item.key)) {
          // 初始化数据可能没有key ,加上左侧数据的key
          selectList.value.forEach((tim) => {
            if (!tim.key && tim.id === itemRealKey) {
              tim.key = item.key;
            }
          });
        }
      });
      treeCheckedKeys.value = [...treeCheckedKeys.value];
    }
  }
}
/**
 * 搜索时，获取所有需要展开的节点
 */
function getExpandedKeys(data, expandedKeys, loadedKeys) {
  if (data && data.length > 0) {
    data.map((item) => {
      if (item.children && item.children.length > 0) {
        expandedKeys.push(item.id);
        loadedKeys.push(item.id);
        getExpandedKeys(item.children, expandedKeys, loadedKeys);
      }
      return item;
    });
  }
}
/**
 * 展开/收起节点
 */
function onExpand(expandedKeys) {
  treeExpandedKeys.value = [...expandedKeys];
}
/**
 * 节点加载完毕
 */
function onLoad(loadedKeys) {
  treeLoadedKeys.value = [...loadedKeys];
}
// 存储每个页签加载所需数据
const tempTabDataMap = new Map();
// 控制部门树显示
const showDeptTree = ref(true);
/**
 * 缓存页签切换后页签显示所需的必要数据，用于切换回来时否需要重新加载数据
 */
function initMapData(newTab) {
  const tabIdMap = {
    [tabsMap.dept.id]: tabsMap.dept,
    [tabsMap.group.id]: tabsMap.group,
    [tabsMap.role.id]: tabsMap.role,
    [tabsMap.position.id]: tabsMap.position
  };
  const newTabObj = tabIdMap[newTab] || null;
  const newTabType = newTabObj?.type || null;
  if (newTabType !== 'dept' && props.viewType.value === 'table') {
    showDeptTree.value = false;
  }
  // 存储当前页签加载所需的相关参数
  tempTabDataMap.set(`${currentTab}selectOptionId`, selectOptionId.value);
  tempTabDataMap.set(`${currentTab}keyword`, keyword.value);
  tempTabDataMap.set(`${currentTab}pagination`, proxy.$lodash.cloneDeep(pagination));
  tempTabDataMap.set(`${currentTab}userTableList`, userTableList.value);
  tempTabDataMap.set(`${currentTab}selectOption`, selectOption.value);
  tempTabDataMap.set(`${currentTab}selectedRowKeys`, selectedRowKeys.value);
  // 重置页签加载所需的相关参数
  emptyTable();
  // 从缓存Map中获取新页签加载所需参数值
  if (tempTabDataMap.has(`${newTabType}keyword`)) {
    keyword.value = tempTabDataMap.get(`${newTabType}keyword`);
  }
  if (tempTabDataMap.has(`${newTabType}pagination`)) {
    const tempPagination = tempTabDataMap.get(`${newTabType}pagination`);
    pagination.current = tempPagination.current;
    queryParam.pageParameter.page = tempPagination.current;
    pagination.total = tempPagination.total;
  }
  if (tempTabDataMap.has(`${newTabType}userTableList`)) {
    userTableList.value = tempTabDataMap.get(`${newTabType}userTableList`);
  }
  if (tempTabDataMap.has(`${newTabType}selectOption`)) {
    selectOption.value = tempTabDataMap.get(`${newTabType}selectOption`);
  }
  // if (tempTabDataMap.has(`${newTabType}selectedRowKeys`)) {
  //   selectedRowKeys.value = tempTabDataMap.get(`${newTabType}selectedRowKeys`);
  // }
  if (tempTabDataMap.has(`${newTabType}selectOptionId`)) {
    selectOptionId.value = tempTabDataMap.get(`${newTabType}selectOptionId`);
  }
  setSelectedRowKeys();
}
/**
 * 切换tab页签事件
 */
function onTabChange(val) {
  initMapData(val);
  activeKey.value = val;
  currentTab = tabs.value.filter(({ id }) => id === val)?.[0]?.type;
  if (currentTab === 'dept') {
    keyword.value = keywordDept.value;
    searchResultFlag.value = searchResultFlagDept.value;
  } else if (currentTab === 'group') {
    keyword.value = keywordGroup.value;
    searchResultFlag.value = searchResultFlagGroup.value;
  } else if (currentTab === 'role') {
    keyword.value = keywordRole.value;
    searchResultFlag.value = searchResultFlagRole.value;
  } else if (currentTab === 'position') {
    keyword.value = keywordPosition.value;
    searchResultFlag.value = searchResultFlagPosition.value;
  }
  realExpandedKeys.value = [
    ...new Set([
      ...treeExpandedKeysDept.value,
      ...treeExpandedKeysGroup.value,
      ...treeExpandedKeysRole.value,
      ...treeExpandedKeysPosition.value
    ])
  ];
  if (loadedTabs.indexOf(currentTab) < 0) {
    loadedTabs.push(currentTab);
    setTreeParameter('', '');
    setTreeSearchParameter('');
    autoLoadAsyn();
  } else {
    if (currentTab === 'dept') {
      treeData.value = [...treeDataDept.value];
      treeLoadedKeys.value = [...treeLoadedKeysDept.value];
      // 由于部门树treeData与其他页签的下拉数据源都是treeData,导致重新赋值时树数据错误报错，这里通过延时控制赋值后再显示树
      setTimeout(() => {
        showDeptTree.value = true;
      }, 10);
    } else if (currentTab === 'group') {
      treeData.value = [...treeDataGroup.value];
      treeLoadedKeys.value = [...treeLoadedKeysGroup.value];

      // selectOptionId.value = treeData.value[0].id;
      // treeLoadedKeys.value = [...treeLoadedKeysGroup.value];
    } else if (currentTab === 'role') {
      treeData.value = [...treeDataRole.value];
      treeLoadedKeys.value = [...treeLoadedKeysRole.value];

      // selectOptionId.value = treeData.value[0];
      // treeLoadedKeys.value = [...treeLoadedKeysRole.value];
    } else if (currentTab === 'position') {
      treeData.value = [...treeDataPosition.value];
      treeLoadedKeys.value = [...treeLoadedKeysPosition.value];

      // selectOptionId.value = treeData.value[0];
      // treeLoadedKeys.value = [...treeLoadedKeysPosition.value];
    }
    treeData.value = [...treeData.value];
    treeLoadedKeys.value = [...treeLoadedKeys.value];
  }
  // emptyTable();
}
function emptyTable() {
  selectedRowKeys.value = [];
  selectOptionId.value = null;
  selectOption.value = {};
  userTableList.value = [];
  queryParam.pageParameter.page = 1;
  queryParam.searchParams.searchText = '';
  keyword.value = '';
  pagination.current = 1;
  pagination.total = 0;
  updateCheckboxState();
}
/**
 * 数据加载完成，处理数据
 */
function afterLoadData(res) {
  setTreeData(res.data);
}
/**
 * 处理数据
 */
function setTreeData(data) {
  if (data && data.length > 0) {
    data.map((tim) => {
      tim.disabled = false;
      if (props.selectModel === 'multi') {
        tim.selectable = false;
        if (tim.nodeType === 'org') {
          tim.checkable = false;
        } else if (tim.isLeaf && tim.nodeType !== 'user') {
          tim.disableCheckbox = true;
        } else {
          tim.disableCheckbox = false;
        }
      } else {
        if (tim.nodeType !== 'user') {
          tim.selectable = false;
        } else {
          tim.selectable = true;
        }
      }
      if (tim.nodeType === 'user') {
        tim.key = tim.key + uuid(32);
      }
      if (tim.children) {
        setTreeData(tim.children);
      }
      return tim;
    });
  }
}
/**
 * 点击树节点事件 单击 / 双击（300毫秒内连续点击两次视为双击）
 */
function onSelect(_, { selected, node }) {
  // 记录点击次数
  treeClickCount.value += 1;
  // 单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
  if (treeClickCount.value >= 2) {
    return;
  }
  // 计时器,计算300毫秒为单位,可自行修改
  window.setTimeout(() => {
    if (treeClickCount.value === 1) {
      // 把次数归零
      treeClickCount.value = 0;
      // 单击事件
      if (selected) {
        selectListMap = {};
        selectListMap[node.id] = { ...node };
        selectList.value = [];
        selectList.value = [{ ...node }];
      } else {
        selectListMap = {};
        selectList.value = [];
      }
      setCheckedData();
    } else if (treeClickCount.value > 1) {
      // 把次数归零
      treeClickCount.value = 0;
      // 双击事件
      if (props.selectModel === 'single') {
        if (node.nodeType === 'user') {
          selectListMap = {};
          selectListMap[node.id] = { ...node };
          selectList.value = [];
          selectList.value = [{ ...node }];
          setCheckedData();
          onConfirm();
        }
      }
    }
  }, 300);
}
/**
 * 多选点击复选框事件
 */
function onCheck(checkedKeys, { checked, checkedNodes, node }) {
  /*
    1、勾选未加载子节点的节点时，通过改变展开节点先触发异步加载；
    2、(当前节点及子节点的)勾选效果在子节点加载完成后，根据当前节点的checked设置
  */
  if (!node.isLeaf && !treeLoadedKeys.value.includes(node.id)) {
    treeExpandedKeys.value = [...treeExpandedKeys.value, node.id];
    return;
  }
  // 根据当前节点的子节点选中状态区分当前操作为取消全选用户
  if (checked && treeLoadedKeys.value.includes(node.id)) {
    if (props.checkChildenNode) {
      checkNodes(node.children);
    }
    // 递归当前节点的子节点选中状态
    let unCheckedNodeCount = 0;
    const checkedNodeChildrenStatus = (list) => {
      if (!list) return;
      list.forEach((item) => {
        if (item.attributes && item.nodeType === 'user' && !selectListMap[item.id]) {
          unCheckedNodeCount = unCheckedNodeCount + 1;
        }
        if (unCheckedNodeCount === 0 && item.children && item.children.length > 0) {
          checkedNodeChildrenStatus(item.children);
        }
      });
    };
    checkedNodeChildrenStatus(node.children);
    // const unCheckedNodeCount = node.children.filter((item) => item.nodeType === 'user' && !selectListMap[item.id])?.length;
    if (!unCheckedNodeCount) {
      setUnSelectList(node);
      setCheckedData();
      return;
    }
  }
  const checkedUsers = checkedNodes.filter((checkedNode) => checkedNode.nodeType === 'user');
  if (props.maxSelect > 0 && checkedUsers.length > props.maxSelect) {
    proxy.$message.warning(`已设置最多选择${props.maxSelect}个人员！`);
    setCheckedData();
  } else {
    if (checked) {
      // 勾选部门节点，仅选择直属于该部门的人员
      const nodes = node.children && node.children.length > 0 ? node.children : [{ ...node }];
      setSelectList(nodes);
      setCheckedData();
    } else {
      setUnSelectList(node);
      setCheckedData();
    }
  }
}
async function checkNodes(childrens) {
  const loadedKeys = [];
  childrens.forEach((node) => {
    if (!node.isLeaf && !treeLoadedKeys.value.includes(node.key)) {
      loadedKeys.push(node.key);
    }
    if (!node.isLeaf && !needCheckedKeys.includes(node.key)) {
      needCheckedKeys.push(node.key);
    }
  });
  loadChildren(childrens).then(() => {
    const keys = childrens.map((item) => {
      if (!item.isLeaf) {
        return item.key;
      }
      return null;
    });
    // treeExpandedKeys.value = [...treeExpandedKeys.value, ...keys];
    treeLoadedKeys.value = [...treeLoadedKeys.value, ...keys];
  });
}
/**
 * 多选选中节点时，处理右侧列表数据
 */
function setSelectList(nodes) {
  if (nodes) {
    nodes.map((tim) => {
      if (!selectListMap[tim.id] && tim.nodeType === 'user') {
        const item = proxy.$lodash.cloneDeep(tim);
        selectList.value.push(item);
        selectListMap[tim.id] = item;
        selectList.value = [...selectList.value];
      }
      if (props.checkChildenNode) {
        setSelectList(tim.children);
      }
      return tim;
    });
  }
}
/**
 * 多选取消选中节点时，处理右侧列表数据
 */
function setUnSelectList(node) {
  const childrenIds = [];
  getTarget(treeData.value, node.id, childrenIds);
  selectList.value = selectList.value.filter((item) => !childrenIds.includes(item.id));
  childrenIds.map((item) => {
    delete selectListMap[item];
    return item;
  });
}
function getTarget(data, id, childrenIds) {
  if (data && data.length > 0 && id) {
    data.map((item) => {
      if (item.id === id) {
        childrenIds.push(item.id);
        if (item.children) {
          getChildren(item.children, childrenIds);
        }
      } else {
        if (item.children) {
          getTarget(item.children, id, childrenIds);
        }
      }
      return item;
    });
  }
}
function getChildren(data, childrenIds) {
  if (data && data.length > 0) {
    data.map((item) => {
      childrenIds.push(item.id);
      if (item.children) {
        getChildren(item.children, childrenIds);
      }
      return item;
    });
  }
}
/**
 * 设置树选中节点
 */
function setCheckedData() {
  const list = [];
  selectList.value.map((tim) => {
    list.push(tim.id);
    return tim;
  });
  const keyList = [];
  getAllKeys(treeData.value, list, keyList);
  treeCheckedKeys.value = keyList;
}
function getAllKeys(data, idList, keyList) {
  if (data && data.length > 0) {
    data.map((item) => {
      if (idList.includes(item.id)) {
        keyList.push(item.key);
      }
      if (item.children) {
        getAllKeys(item.children, idList, keyList);
      }
      return item;
    });
  }
}
/**
 * 默认值只有ids时，加载默认数据的处理
 */
function loadDefaultValue(ids) {
  if (ids) {
    let userIds = [];
    userIds = ids.split(';');
    findInitUserInfo(userIds);
  }
}
/**
 * 根据ids获取用户信息
 */
function findInitUserInfo(userIds) {
  emptySelect();
  const allAttributes = getExtraAttributes(props.defaultValue);
  const attrKeys = Object.keys(allAttributes);
  httpRequest(props.getInitUserInfoUrl, userIds, props.getInitUserInfoMethod).then((res) => {
    if (res.success) {
      res.data.map((tim, i) => {
        if (tim.id) {
          // 设置默认的附加信息
          const attributes = {};
          attrKeys.forEach((key: string) => {
            if (allAttributes[key][i]) {
              attributes[key] = allAttributes[key][i];
            }
          });
          selectList.value.push({
            id: tim.id,
            nodeType: 'user',
            title: tim.name,
            // key: tim.id,
            isLeaf: true,
            children: [],
            attributes: {
              deptid: tim.deptid,
              deptname: tim.deptname,
              ...attributes
            }
          });
          selectListMap[tim.id] = tim;
          treeCheckedKeys.value.push(tim.id);
        }
        return tim;
      });
    }
    const result = setResultData();
    setTimeout(() => {
      $emit('defaultBack', result);
    }, 100);
  });
}
/**
 * 默认值有ids和names时，加载默认数据的处理
 */
function initDataNotHttp(data) {
  emptySelect();
  const ids = data.ids.split(';');
  const allAttributes = getExtraAttributes(props.defaultValue);
  if (ids.length > 0) {
    const names = data.names.split(';');
    let deptIds = [];
    let deptNames = [];
    const nos = [];
    const loginNames = [];
    const deptNamePaths = [];
    const secretLevels = [];
    if (data.deptid && data.deptname) {
      deptIds = data.deptid.split(';');
      deptNames = data.deptname.split(';');
      setInitData(ids, names, deptIds, deptNames, nos, loginNames, deptNamePaths, secretLevels, allAttributes);
    } else {
      const userIds = data.ids.split(';');
      getInitUserInfoFunc(
        {
          url: props.getInitUserInfoUrl,
          parameter: userIds,
          method: props.getInitUserInfoMethod
        },
        (result) => {
          result.map((item) => {
            deptIds.push(item.deptid);
            deptNames.push(item.deptname);
            nos.push(item.no);
            loginNames.push(item.loginName);
            deptNamePaths.push(item.deptNamePath);
            secretLevels.push(item.secretLevel);
            return item;
          });
          setInitData(ids, names, deptIds, deptNames, nos, loginNames, deptNamePaths, secretLevels, allAttributes);
        },
        () => {
          setInitData(ids, names, deptIds, deptNames, nos, loginNames, deptNamePaths, secretLevels, allAttributes);
        }
      );
    }
  }
}
// 从defaultValue 中获取附加信息
function getExtraAttributes(data = {}) {
  const attributesMap = {};
  let attrList = [];
  if (typeof props.showMoreUserInfo == 'boolean') {
    attrList = props.moreUserInfo;
  } else {
    attrList = props.showMoreUserInfo;
  }
  attrList.forEach((key) => {
    if (data[key]) {
      attributesMap[key] = data[key].split(';');
    }
  });
  return attributesMap;
}
/**
 * 根据ids获取用户信息
 */
function getInitUserInfoFunc(param, successCallback, errorCallback) {
  httpRequest(param.url, param.parameter, param.method)
    .then((res) => {
      if (res.success && res.data) {
        if (successCallback) {
          successCallback(res.data);
        }
      } else {
        if (errorCallback) {
          errorCallback();
        }
      }
    })
    .catch(() => {
      if (errorCallback) {
        errorCallback();
      }
    });
}
/**
 * 处理默认数据
 */
// eslint-disable-next-line max-params
function setInitData(ids, names, deptIds, deptNames, nos, loginNames, deptNamePaths, secretLevels, allAttributes) {
  const list = [];
  selectList.value = [];
  selectListMap = {};
  const attrKeys = Object.keys(allAttributes);
  ids.map((tim, i) => {
    const item = {
      id: tim,
      nodeType: 'user',
      title: names[i],
      // key: tim,
      isLeaf: true,
      children: [],
      attributes: {
        deptid: deptIds[i] ? deptIds[i] : '',
        deptname: deptNames[i] ? deptNames[i] : '',
        no: nos[i] ? nos[i] : '',
        loginName: loginNames[i] ? loginNames[i] : '',
        deptNamePath: deptNamePaths[i] ? deptNamePaths[i] : '',
        secretLevel: secretLevels[i] ? secretLevels[i] : ''
      }
    };
    // 设置默认的附加信息
    attrKeys.forEach((key) => {
      if (allAttributes[key][i]) {
        item.attributes[key] = allAttributes[key][i];
      }
    });
    selectList.value.push(item);
    list.push(tim);
    selectListMap[tim] = item;
    return tim;
  });
  treeCheckedKeys.value = list;
}
/**
 * 删除右侧列表单条数据
 */
function handleDelItem(e, item) {
  e.stopPropagation();
  const newSelectList = [];
  for (let i = 0; i < selectList.value.length; i++) {
    if (selectList.value[i].id !== item.id) {
      newSelectList.push(selectList.value[i]);
    }
  }
  selectList.value = newSelectList;
  delete selectListMap[item.id];
  selectedRowKeys.value = selectedRowKeys.value.filter((key) => key.indexOf(item.id) === -1);
  setCheckedData();
  updateCheckboxState();
}
/**
 * 清空右侧列表
 */
function handleDelTotal() {
  emptySelect();
  selectedRowKeys.value = [];
  updateCheckboxState();
}
/**
 * 清空选中人员
 */
function emptySelect() {
  treeCheckedKeys.value = [];
  selectList.value = [];
  selectListMap = {};
}
/**
 * 清除查询条件
 */
function emptyQuery() {
  currentTab = tabs.value[0].type;
  loadedTabs = [tabs.value[0].type];
  setTreeParameter('', '');
  setTreeSearchParameter('');
  activeKey.value = '1';
  keyword.value = '';
  // #31107缺陷时追加此行，暂未发现注释掉的影响
  // autoLoadAsyn();
}
/**
 * 点击确定事件
 */
function onConfirm() {
  const result = setResultData();
  if (result.ids) {
    $emit('callBack', result, selectList.value);
  } else {
    $emit('callBack', {});
  }
  emptyQuery();
  // visible.value = false;
  $emit('close');
}
/**
 * 处理返回的数据格式
 */
function setResultData() {
  let ids = '';
  let names = '';
  let deptid = '';
  let deptname = '';
  let deptNamePath = '';
  if (selectList.value && selectList.value.length > 0) {
    selectList.value.map((res, i) => {
      if (i > 0) {
        ids += ';';
        names += ';';
        if (res.attributes) {
          deptid += ';';
          deptname += ';';
          deptNamePath += ';';
        }
      }
      ids += res.id;
      names += res.title;
      if (res.attributes) {
        deptid += res.attributes.deptid;
        deptname += res.attributes.deptname;
        deptNamePath += res.attributes.deptNamePath;
      }
      return res;
    });
  }
  let result = null;
  if (deptid) {
    result = { ids, names, deptid, deptname, deptNamePath };
  } else {
    result = { ids, names };
  }
  return result;
}

/**
 * 下拉框filterOption
 */
function filterOption(input, option) {
  return option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

/**
 * 下拉框改变切换角色/群组/岗位
 */
function handleChange(value) {
  selectOptionId.value = value;
  selectOption.value = treeData.value.filter((item) => item.id === value)[0];
  getUserList(selectOption.value);
}
/**
 * 获取参数
 * @param id
 */
/**
 * 快速查询逻辑
 * @param value 搜索框数据
 */
function handleKeyWordQuery(value) {
  if (!selectOptionId.value) {
    proxy.$message.warning(`请选择${placeholderMap[currentTab]}`);
    return;
  }
  queryParam.searchParams.searchText = value;
  userTableList.value = [];
  queryParam.pageParameter.page = 1;
  pagination.current = 1;
  getUserList(selectOption.value);
}
function setParameter() {
  const param = {
    ...queryParam
  };
  if (Object.keys(props.customParam)) {
    Object.assign(
      param.searchParams,
      {
        currentTab,
        viewScope: props.viewScope,
        id: selectOptionId.value,
        viewSystemUser: props.viewSystemUser,
        secretLevel: props.secretLevel,
        userSecretLevel: props.userSecretLevel
      },
      props.customParam
    );
  }
  return param;
}

/**
 * 获取 角色/群组/岗位 用户分页列表
 */
function getUserList(node) {
  // 获取查询参数
  const param = setParameter();
  if (!node.nodeType) {
    proxy.$message.warning('请选择数据查询！');
  }
  tableLoading.value = true;
  listCommonSelectUserByPage(param)
    .then((res) => {
      if (res.success && res.data && res.data.result.length > 0) {
        // 处理数据格式
        res.data.result = formatData(res.data.result);
        pagination.total = res.data.pageParameter.totalCount;
        // 扩展：根据业务需要过滤可选人员数据
        if (props.filterUser) {
          res.data.result = props.filterUser(res.data.result);
        }
        userTableList.value = [...res.data.result];
        // 回显选中项数据
        setSelectedRowKeys();
      } else {
        selectedRowKeys.value = [];
        userTableList.value = [];
        if (proxy.$objIsNotBlank(keyword.value)) {
          proxy.$message.warning(res.errorDesc || '未查询到匹配数据！');
          searchResultFlag.value = true;
        } else if (res.errorDesc || node?.title) {
          proxy.$message.warning(res.errorDesc || `${node?.title ?? ''} 节点下无数据。`);
          userTableList.value = [];
          pagination.total = 0;
        }
      }
    })
    .finally(() => {
      tableLoading.value = false;
      updateCheckboxState();
    });
}
function formatData(list) {
  const newList = list.map((item) => {
    item.nodeType = 'user';
    item.key = item.id + uuid(32);
    return item;
  });
  return newList;
}
/**
 * 设置左侧侧角色/群组/岗位用户列表选中项
 */
function setSelectedRowKeys() {
  const selectedKeys = userTableList.value.reduce((pre, cur) => {
    if (selectListMap[cur.id]) {
      pre.push(cur.key);
    }
    return pre;
  }, []);
  selectedRowKeys.value = [...selectedKeys];
}
/**
 * 当手动勾选并且值发生改变时触发的事件
 */
function onSelectChange(record, selected, selectedRows) {
  if (props.selectModel === 'multi') {
    const selectIds = Object.keys(selectListMap);
    if (selected) {
      // 选中
      if (!selectIds.includes(record.id)) {
        if (props.maxSelect > 0 && selectIds.length > props.maxSelect - 1) {
          proxy.$message.warning(`已设置最多选择${props.maxSelect}个角色！`);
        } else {
          setSelectList([record]);
          selectedRowKeys.value.push(record.key);
        }
      } else {
        selectedRowKeys.value.push(record.key);
      }
    } else {
      // 取消选中
      if (selectListMap[record.id]) {
        selectList.value = selectList.value.filter((item) => item.id !== record.id);
        delete selectListMap[record.id];
        selectedRowKeys.value = selectedRowKeys.value.filter((key) => key.indexOf(record.id) === -1);
      }
    }
  } else {
    // 单选直接选中
    selectList.value = selectedRows;
    selectListMap = {
      [record.id]: record
    };
    selectedRowKeys.value = [record.key];
  }
  updateCheckboxState();
}
/**
 * 点击行实现选中
 */
function handleRowSelection(record) {
  const selectIds = Object.keys(selectListMap);
  if (props.selectModel === 'multi') {
    // 多选
    if (!selectIds.includes(record.id)) {
      // 选中
      if (props.maxSelect > 0 && selectIds.length > props.maxSelect - 1) {
        proxy.$message.warning(`已设置最多选择${props.maxSelect}个角色！`);
      } else {
        setSelectList([record]);
        selectedRowKeys.value.push(record.key);
      }
    } else {
      // 取消选中
      if (selectListMap[record.id]) {
        selectList.value = selectList.value.filter((item) => item.id !== record.id);
        delete selectListMap[record.id];
        selectedRowKeys.value = selectedRowKeys.value.filter((key) => key.indexOf(record.id) === -1);
      }
    }
  } else {
    if (!selectListMap[record.id]) {
      // 单选直接选中
      selectList.value = [record];
      selectListMap = {
        [record.id]: record
      };
      selectedRowKeys.value = [record.key];
    } else {
      selectList.value = [];
      selectListMap = {};
      selectedRowKeys.value = [];
    }
  }
  updateCheckboxState();
}

/**
 * 接收并处理分页、排序信息
 * @pagination,  分页信息
 * @filters, 过滤信息
 * @sorter,  排序信息
 * @obj { action: 'paginate' | 'sort' | 'filter' } 操作类型
 */
function handleTableChange(paginationInfo) {
  if (queryParam.pageParameter.page !== paginationInfo.current) {
    queryParam.pageParameter.page = paginationInfo.current; // 页数
    queryParam.pageParameter.rows = paginationInfo.pageSize; // 页数
    if (selectOptionId.value) {
      getUserList(selectOption.value);
    }
  }
}

function updateCheckboxState() {
  if (selectedRowKeys.value.length > 0) {
    if (selectedRowKeys.value.length !== userTableList.value.length) {
      state.checkAll = false;
    } else if (selectedRowKeys.value.length === userTableList.value.length) {
      state.checkAll = true;
    }
  } else {
    state.checkAll = false;
  }
}
// 全选
function handleCheckAllChange(e) {
  if (e.target.checked) {
    // 全选
    selectedRowKeys.value = userTableList.value.map((item) => item.key);
    setSelectList(userTableList.value);
  } else {
    // 取消全选
    selectedRowKeys.value = [];
    // 清空Map中的数据
    userTableList.value.forEach((item) => {
      if (selectListMap[item.id]) {
        delete selectListMap[item.id];
      }
    });
    selectList.value = Object.values(selectListMap);
  }
  updateCheckboxState();
}
function handleDbclickSelection(record) {
  handleRowSelection(record);
  if (props.selectModel === 'single') {
    onConfirm();
  }
}
defineExpose({
  setResultData,
  selectList,
  emptyQuery,
  onConfirm
});
</script>
<style scoped>
.more-user-info {
  display: inline-block;
  width: 280px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: middle;
}
</style>
